/**
 *
 */
package commons.beancopier.internal;

import java.lang.reflect.Array;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

import com.tmall.common.beancopier.AbstractPropertyCopier;
import com.tmall.common.beancopier.BeanCopier;
import com.tmall.common.beancopier.mapper.BeanMapperUtils;
import com.tmall.common.beancopier.mapper.PropertiesMapper;
import com.tmall.common.beancopier.mapper.PropertiesMapperBuilder;


/**
 * @author 陌铭(Phenix Huang)
 *
 */
public class ArrayPropertyCopier extends AbstractPropertyCopier {



    public ArrayPropertyCopier() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ArrayPropertyCopier(PropertiesMapperBuilder mapper, BeanCopier copier) {
        super(mapper, copier);
        // TODO Auto-generated constructor stub
    }

    /*
     *
     * @see net.phenix.comp.util.beancopier.AbstractPropertyCopier#smartCopyProperty(java.lang.Object, java.lang.String, java.lang.Class, java.lang.Object)
     */
    public void smartCopyProperty(Object dest, String propertyName, Class<?> propertyType, Object value) throws Exception {
        Object array = null ;
        if (PropertyUtils.isReadable(dest, propertyName)) {
            array = PropertyUtils.getProperty(dest, propertyName);
        }
        Class<?> componentType = propertyType.getComponentType();
        Map<String, String> propertyMap = BeanMapperUtils.getPropertyNameMap(componentType);
        PropertiesMapper mapper = getPropertyMapper(componentType);
        if (mapper == null) {
            return ;
        }
        BeanMapperUtils.filterProperties(propertyMap, mapper);
        int length = Array.getLength(value);
        if (array == null) {
            array = Array.newInstance(componentType, length);
            if (PropertyUtils.isWriteable(dest, propertyName)) {
                PropertyUtils.setProperty(dest, propertyName, array);
            } else {
                return ;
            }
        }
        for (int i = 0; i < length; i++) {
            Object subSource = Array.get(value, i);
            Object subDest = null ;
            if (subSource != null) {
                subDest = cloneAndFilterObject(dest, subSource, componentType, propertyMap);
            }
            Array.set(array, i, subDest);
        }
        return ;

    }

    /*
     * @see net.phenix.comp.util.beancopier.AbstractPropertyCopier#couldSmartCopy(java.lang.Class)
     */
    @Override
    public boolean couldSmartCopy(Class<?> propertyType) {
        return propertyType.isArray();
    }


}
